package com.revenant.driver.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.blankj.utilcode.util.LogUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.entity.LocalMedia;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.nanchen.compresshelper.CompressHelper;
import com.revenant.driver.R;
import com.revenant.driver.adapter.AddNewDriverInfoAdaper;
import com.revenant.driver.base.BaseActivity;
import com.revenant.driver.bean.Driver.CarHeadNumSelectBean;
import com.revenant.driver.bean.Driver.ColorAndEnergerBean;
import com.revenant.driver.bean.Driver.SearchEmptyBean;
import com.revenant.driver.bean.NewDriverAddInfo;
import com.revenant.driver.bean.ShipperBean.FileUploadBean;
import com.revenant.driver.utils.GsonUtil;
import com.revenant.driver.utils.SPUtils;

import org.angmarch.views.NiceSpinner;
import org.angmarch.views.OnSpinnerItemSelectedListener;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static com.revenant.driver.utils.Constants.Driver_Car_Color;
import static com.revenant.driver.utils.Constants.ImproveCarAndTrailerNewUpdate;
import static com.revenant.driver.utils.Constants.Improve_Car_Head_Num_Beans;
import static com.revenant.driver.utils.Constants.UploadFile;
import static com.revenant.driver.utils.Constants.Warning_Text;

public class BuQuanGuaCheActivity extends BaseActivity {

    @BindView(R.id.tv_device_name)
    TextView tvDeviceName;
    @BindView(R.id.select_carnum)
    NiceSpinner selectarnum;
    @BindView(R.id.new_recyclerviewtwo)
    RecyclerView newRecyclerviewtwo;
    @BindView(R.id.select_three)
    NiceSpinner selectThree;
    @BindView(R.id.new_btn_format)
    Button newBtnFormat;
    @BindView(R.id.show_differt_type)
    LinearLayout showDiffertType;
    private String spinnerc = "";
    private String spinnercarnum = "";
    private List<String> listNameTwo = Arrays.asList(
            "挂车行驶证正本",
            "挂车行驶证副本",
            "挂车营运证"
    );
    private List<Integer> listImageTwo = Arrays.asList(
            R.mipmap.xingshizhengforeground,
            R.mipmap.xingshizhengback,
            R.mipmap.congyezigezhneg
    );


    List<String> colorTwo = new ArrayList<>();
    List<String> colorCodeTwo = new ArrayList<>();


    List<String> carHeadname = new ArrayList<>();
    List<String> carHeadCodename = new ArrayList<>();


    private List<NewDriverAddInfo> listuserstwo = new ArrayList<>();


    private Context context;


    private int type = 0;
    private int cartbuqanId = -1;
    private List<String> typeTitle = new LinkedList<>(Arrays.asList("添加挂车", "完善挂车"));


    private AddNewDriverInfoAdaper adapertwo;

    private int selecttype = -1;
    private int selectindex = -1;

    private List<LocalMedia> selectList = new ArrayList<>();
    private int isImages = -1;

    @Override
    public int getContentViewResId() {
        context = this;
        return R.layout.activity_buquangauhce;
    }

    @Override
    public void initView() {


        Bundle extra = getIntent().getExtras();
        type = extra.getInt("cartype", 0);
        cartbuqanId = extra.getInt("cartbuqanId", -1);
        setcenterTitle(typeTitle.get(type));

        tvDeviceName.setText(Warning_Text);
        tvDeviceName.setSelected(true);

        if (type == 1) {
            carHeadname.add("请选择");
            carHeadCodename.add("-1");
            select_head_num();
            showDiffertType.setVisibility(View.VISIBLE);
        }


        adapertwo = new AddNewDriverInfoAdaper();
        newRecyclerviewtwo.setLayoutManager(new GridLayoutManager(context, 2));
        newRecyclerviewtwo.setAdapter(adapertwo);


        for (int i = 0; i < listNameTwo.size(); i++) {
            NewDriverAddInfo user = new NewDriverAddInfo();
            user.setImage(listImageTwo.get(i));
            user.setTitle(listNameTwo.get(i));
            user.setImageUrl("");
            listuserstwo.add(user);
        }
        adapertwo.addData(listuserstwo);

        adapertwo.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                selecttype = 2;
                selectindex = position;
                showBottomSheetDialog(BuQuanGuaCheActivity.this);
            }
        });

        selectarnum.setOnSpinnerItemSelectedListener(new OnSpinnerItemSelectedListener() {
            @Override
            public void onItemSelected(NiceSpinner parent, View view, int position, long id) {
                if (position == 0) {
                    spinnercarnum = "";
                    cartbuqanId = -1;
                } else {
                    spinnercarnum = carHeadCodename.get(position);
                    cartbuqanId = Integer.valueOf(spinnercarnum);

                }
            }
        });


        selectThree.setOnSpinnerItemSelectedListener(new OnSpinnerItemSelectedListener() {
            @Override
            public void onItemSelected(NiceSpinner parent, View view, int position, long id) {
                if (position == 0) {
                    spinnerc = "";
                } else {
                    spinnerc = colorCodeTwo.get(position);

                }
            }
        });

        newBtnFormat.setText("提交审核");
        getColor();

    }

    @Override
    public void leftbarclick() {
        finish();
    }

    @Override
    public void initData() {
        colorTwo.add("请选择");
        colorCodeTwo.add("-1");


    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }


    @OnClick({R.id.new_btn_format})
    public void onViewClicked(View view) {
        switch (view.getId()) {

            case R.id.new_btn_format:

                isImages = -1;
                for (int i = 0; i < listNameTwo.size(); i++) {
                    if (adapertwo.getData().get(i).getImageUrl().isEmpty()) {
                        showToast("请输入" + listNameTwo.get(i));
                        isImages = 0;
                        break;
                    }
                }
                if (isImages != 0 && selectThree.getSelectedIndex() < 1) {
                    showToast("请输入" + "车牌颜色");
                } else if (selectThree.getSelectedIndex() > 0 && selectThree.getSelectedIndex() > 0 && isImages != 0) {

                    if (cartbuqanId == -1) {
                        showToast("请选择头车信息");
                    } else {
                        String photod = adapertwo.getData().get(0).getImageUrl();
                        String photoe = adapertwo.getData().get(1).getImageUrl();
                        String photof = adapertwo.getData().get(2).getImageUrl();
                        if (!(photod.isEmpty() ^ photoe.isEmpty() ^ photof.isEmpty() ^ spinnerc.isEmpty())) {
                            showDig();
                            improvecartype(
                                    photod,
                                    photoe,
                                    photof,
                                    spinnerc,
                                    cartbuqanId
                            );
                        } else {
                            showToast("补全挂车信息");
                        }
                    }


                }
                break;
        }
    }


    private void getColor() {

        OkGo.<String>get(Driver_Car_Color)

                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        ColorAndEnergerBean colorAndEnergerBean = GsonUtil.parseJsonWithGson(response.body(), ColorAndEnergerBean.class);
                        if (colorAndEnergerBean.getCode().equals("0")) {
                            if (colorAndEnergerBean.getData().getColList() != null && colorAndEnergerBean.getData().getColList().size() > 0) {
                                for (int i = 0; i < colorAndEnergerBean.getData().getColList().size(); i++) {
                                    colorTwo.add(colorAndEnergerBean.getData().getColList().get(i).getName());
                                    colorCodeTwo.add(colorAndEnergerBean.getData().getColList().get(i).getCode());
                                }
                                selectThree.attachDataSource(colorTwo);
//                                for (int i = 0; i < colorCodeTwo.size(); i++) {
//                                    if (colorCodeTwo.get(i).equals(spinnerc)) {
//                                        selectThree.setSelectedIndex(i);
//                                    }
//                                }


                            }

                        } else {
                        }

                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                    }

                    @Override
                    public void onFinish() {
                        super.onFinish();
                    }
                });
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                    selectList = PictureSelector.obtainMultipleResult(data);
                    for (LocalMedia media : selectList) {
                        if (!selectList.isEmpty()) {
                            showDig();
//                            uploadAvatar(media.getPath());
                            String url = media.getPath().startsWith("content://") ? media.getAndroidQToPath() : media.getPath();
                            uploadAvatar(url, selectindex);
                        }
                    }
                    break;
            }
        }
    }

    private void uploadAvatar(final String path, int select) {
        File file = new File(path);
        File newfile = CompressHelper.getDefault(context).compressToFile(file);

        OkGo.<String>post(UploadFile)
                .tag(this)
                .isMultipart(true)

                .params("file", newfile)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        dismissDig();
                        if (response.code() == 200) {
                            FileUploadBean fileUploadBean = GsonUtil.parseJsonWithGson(response.body(), FileUploadBean.class);
                            if (fileUploadBean.getCode().equals("0")) {
                                if (selecttype == 2) {
                                    adapertwo.getData().get(select).setImageUrl(fileUploadBean.getData().getUrl());
                                    adapertwo.getData().get(select).setSelecttype(0);
                                    adapertwo.notifyItemChanged(select);
                                }


                            } else {
                                showToast(fileUploadBean.getMsg());
                            }
                        } else {
                            showToast(response.message());
                        }

                    }

                    @Override
                    public void onError(Response<String> response) {
                        dismissDig();
                        super.onError(response);
                        showToast(response.message());
                    }
                });
    }

    private void improvecartype(
            String trailerLicenseImgJust,
            String trailerLicenseImgBack,
            String trailerOperationCertificate,
            String trailerVehiclePlateColorCode,
            int carDriverId

    ) {
        OkGo.<String>post(ImproveCarAndTrailerNewUpdate)
                .params("trailerLicenseImgJust", trailerLicenseImgJust)
                .params("trailerLicenseImgBack", trailerLicenseImgBack)
                .params("trailerOperationCertificate", trailerOperationCertificate)
                .params("trailerVehiclePlateColorCode", trailerVehiclePlateColorCode)
                .params("carDriverId", carDriverId)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        LogUtils.d("testAAAAAA" + response.body());
                        dismissDig();
                        if (!response.body().isEmpty()) {
                            SearchEmptyBean g = GsonUtil.parseJsonWithGson(response.body(), SearchEmptyBean.class);
                            if (g != null) {
                                if (g.getCode() != null) {
                                    if (g.getCode().equals("0")) {
                                        showToast(g.getMsg());
                                        finish();
                                        Bundle bundle=new Bundle();
                                        bundle.putInt("buquanguachetype",0);
                                        startActivity(DriverVehicleManageActivity.class,bundle);
                                    } else {
                                        showToast(g.getMsg());
                                    }
                                }
                            }
                        }


                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        dismissDig();
                    }
                });
    }

    private void select_head_num() {
        OkGo.<String>get(Improve_Car_Head_Num_Beans)
                .params("driverId", SPUtils.getAccounId(context))
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        if (response.code() == 200) {
                            CarHeadNumSelectBean personal = GsonUtil.parseJsonWithGson(response.body(), CarHeadNumSelectBean.class);
                            if (Integer.valueOf(personal.getCode()) == 0) {

                                if (personal.getData().getIsConsummate() == 0) {
                                    if (personal.getData().getCarNoList() != null) {
                                        if (personal.getData().getCarNoList().size() > 0) {
                                            for (int i = 0; i < personal.getData().getCarNoList().size(); i++) {
                                                carHeadname.add(personal.getData().getCarNoList().get(i).getCarNo());
                                                carHeadCodename.add(String.valueOf(personal.getData().getCarNoList().get(i).getCarDriverId()));
                                            }

                                            selectarnum.attachDataSource(carHeadname);
                                        }
                                    }

                                }

                            } else {

                            }

                        }

                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        showToast(response.message());
                    }
                });
    }
}
